package com.mcp.mslocalmcp.controller;

import com.mcp.mslocalmcp.service.MySqlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/health")
@CrossOrigin(origins = "*")
public class HealthController {
    
    private static final Logger logger = LoggerFactory.getLogger(HealthController.class);
    
    @Autowired
    private MySqlService mySqlService;
    
    @GetMapping
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("service", "MySQL MCP Server");
        response.put("timestamp", System.currentTimeMillis());
        
        try {
            boolean dbConnected = mySqlService.testConnection();
            response.put("database", dbConnected ? "CONNECTED" : "DISCONNECTED");
            
            if (dbConnected) {
                Map<String, Object> dbInfo = mySqlService.getDatabaseInfo();
                response.put("databaseInfo", dbInfo);
            }
        } catch (Exception e) {
            logger.error("健康检查失败: {}", e.getMessage(), e);
            response.put("database", "ERROR");
            response.put("error", e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    @GetMapping("/database")
    public ResponseEntity<Map<String, Object>> databaseStatus() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Map<String, Object> dbInfo = mySqlService.getDatabaseInfo();
            response.putAll(dbInfo);
        } catch (Exception e) {
            logger.error("获取数据库状态失败: {}", e.getMessage(), e);
            response.put("error", e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
} 